package com.ruoyi.basic.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.basic.domain.TbExchangeRate;
import com.ruoyi.basic.domain.TbHoliday;
import com.ruoyi.basic.domain.TbMonthlyExchangeRate;
import com.ruoyi.basic.domain.dto.HolidayRespDTO;
import com.ruoyi.basic.domain.dto.TbExchangeRateRespDTO;
import com.ruoyi.basic.service.ITbExchangeRateService;
import com.ruoyi.basic.service.ITbHolidayService;
import com.ruoyi.basic.service.ITbMonthlyExchangeRateService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.CurrenyType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 汇率Service接口
 * 
 * @author ruoyi
 * @date 2022-09-04
 */
@Component("rateTask")
public class TbExchangeRateTask
{
    @Autowired
    private ITbExchangeRateService rateService;
    @Autowired
    private ITbMonthlyExchangeRateService monthlyExchangeRateService;
    @Autowired
    private ITbHolidayService holidayService;
    @Autowired
    private ISysDictTypeService sysDictTypeService;

    /**
     * 定时抓取网络汇率数据
     */
    public void ryNoParams()
    {
        // 1、访问接口
        String respStr = HttpUtils.sendGet("https://www.mxnzp.com/api/exchange_rate/list", "app_id=itqlgkrfnpfluvfd&app_secret=cHF0eWNIdFZ6eHdXZ0wzT0tWUVFtZz09");
        TbExchangeRateRespDTO respDTO = JSONUtil.toBean(respStr, TbExchangeRateRespDTO.class);
        // 2、判断返回结果
        if(1 != respDTO.getCode()){
            // 2-1、返回失败，抛出异常
            throw new ServiceException("汇率接口请求失败");
        }
        // 2-2、返回成功，解析数据
        List<TbExchangeRate> dataList = respDTO.getData();
        List<TbExchangeRate> rateList = new ArrayList<>();
        Date now = DateUtils.getNowDate();
        dataList = dataList.stream().map(a ->{
            a.setRateDate(now);
            return a;
        }).collect(Collectors.toList());
        List<TbExchangeRate> rates = new ArrayList<>();
        String rateDate = DateUtils.parseDateToStr("yyyy-MM-dd",now);
        // 根据月份查询月汇率
        TbExchangeRate query = new TbExchangeRate();
        query.setRateDateStr(rateDate);
        List<TbExchangeRate> oldRates= rateService.listByCondition(query);
        Map<String, TbExchangeRate> rateMap = new HashMap<>();
        if(!oldRates.isEmpty()){
            rateMap = oldRates.stream().collect(Collectors.toMap(item -> DateUtils.parseDateToStr("yyyy-MM-dd", item.getRateDate()) + '-' + item.getFrom() + '-' + item.getTo(), i -> i, (k1, k2) -> k2));
        }
        Map<String, TbExchangeRate> finalRateMap = rateMap;
        List<SysDictData> datas = sysDictTypeService.selectDictDataByType("currency_type");
        List<String> currencyTypes = datas.stream().map(SysDictData::getDictValue).distinct().collect(Collectors.toList());
        // 只保存汇率目标为人民币的汇率
        rateList = dataList.stream().filter(item -> (CurrenyType.CNY.getCode().equals(item.getTo()) && currencyTypes.contains(item.getFrom()))).collect(Collectors.toList());
        rateList.forEach(item->{
            String key = rateDate + '-'+item.getFrom()+'-'+item.getTo();
            TbExchangeRate rate = null;
            if(finalRateMap.containsKey(key)){
                rate = finalRateMap.get(key);
            }else{
                rate = new TbExchangeRate();
                BeanUtils.copyProperties(item,rate);
                rate.setRateDate(DateUtils.parseDate(rateDate));
            }
            rates.add(rate);
        });
        rateService.saveOrUpdateBatch(rates);
    }

    public void rateMonthly()
    {
        String respStr = HttpUtils.sendGet("https://www.mxnzp.com/api/exchange_rate/list", "app_id=itqlgkrfnpfluvfd&app_secret=cHF0eWNIdFZ6eHdXZ0wzT0tWUVFtZz09");
        TbExchangeRateRespDTO respDTO = JSONUtil.toBean(respStr, TbExchangeRateRespDTO.class);
        // code为1 请求成功
        if(1 != respDTO.getCode()){
            throw new ServiceException("汇率接口请求失败");
        }

        // 保存
        List<TbExchangeRate> dataList = respDTO.getData();
        List<TbExchangeRate> rateList = new ArrayList<>();
        Date now = DateUtils.getNowDate();
        dataList = dataList.stream().map(a ->{
            a.setRateDate(now);
            return a;
        }).collect(Collectors.toList());
        List<TbMonthlyExchangeRate> monthlyExchangeRates = new ArrayList<>();
        String month = DateUtils.parseDateToStr("yyyy-MM",now);
        // 根据月份查询月汇率
        List<TbMonthlyExchangeRate> oldMonthRates= monthlyExchangeRateService.listByMonth(month);
        Map<String, TbMonthlyExchangeRate> monthlyRateMap = new HashMap<>();
        if(!oldMonthRates.isEmpty()){
            monthlyRateMap = oldMonthRates.stream().collect(Collectors.toMap(item -> DateUtils.parseDateToStr("yyyy-MM", item.getRateDate()) + '-' + item.getFrom() + '-' + item.getTo(), i -> i, (k1, k2) -> k2));
        }
        Map<String, TbMonthlyExchangeRate> finalMonthlyRateMap = monthlyRateMap;
        List<SysDictData> datas = sysDictTypeService.selectDictDataByType("currency_type");
        List<String> currencyTypes = datas.stream().map(SysDictData::getDictValue).distinct().collect(Collectors.toList());
        // 只保存汇率目标为人民币的和跟字典匹配的汇率
        rateList = dataList.stream().filter(item -> (CurrenyType.CNY.getCode().equals(item.getTo()) && currencyTypes.contains(item.getFrom()))).collect(Collectors.toList());
        rateList.forEach(item->{
            String key = month + '-'+item.getFrom()+'-'+item.getTo();
            TbMonthlyExchangeRate monthlyExchangeRate = null;
            if(finalMonthlyRateMap.containsKey(key)){
                monthlyExchangeRate = finalMonthlyRateMap.get(key);
            }else{
                monthlyExchangeRate = new TbMonthlyExchangeRate();
                BeanUtils.copyProperties(item,monthlyExchangeRate);
                monthlyExchangeRate.setRateDate(DateUtils.parseDate(month));
            }
            monthlyExchangeRates.add(monthlyExchangeRate);
        });
        monthlyExchangeRateService.saveOrUpdateBatch(monthlyExchangeRates);
    }
    public void ryNoParams2()
    {
        List<TbHoliday> dataList = new ArrayList<>();
        //for (int i = 2026; i <= 2030; i++) {
            String respStr = HttpUtils.sendGet("http://timor.tech/api/holiday/year/2022/", null);
            HolidayRespDTO respDTO = JSONUtil.toBean(respStr, HolidayRespDTO.class);
            // code为1 请求成功
            if(0 != respDTO.getCode()){
                throw new ServiceException("汇率接口请求失败");
            }

            // 保存

            Map<String, TbHoliday> holiday = respDTO.getHoliday();
            for(String key : holiday.keySet()){
               TbHoliday h = holiday.get(key);
               dataList.add(h);
            }
        //}
        holidayService.saveBatch(dataList);
    }
}
